package com.example.saveword.save_word;

import com.example.saveword.R;
import com.example.saveword.dao.UserDao;
import com.example.saveword.model.User;
import com.example.saveword.utils.JsonUtils;
import com.example.saveword.utils.SPUtils;
import com.example.saveword.utils.ViewUtil;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener{
    TextView btn_login, btn_toRegister;
    EditText et_login_username, et_login_psw;
    RelativeLayout login_view;
    Context context;

    // 数据库操作
    UserDao userDao;

    // 时间监听
    private IntentFilter intentFilter;
    private TimeChangeReceiver timeChangeReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
        setTimerListener();
    }

    private void init() {
        context = this;
        // 初始化背景图片
        SPUtils.put(this, "bg", "bg0");
        // 初始化组件
        btn_login = findViewById(R.id.btn_login);
        btn_toRegister = findViewById(R.id.btn_toRegister);
        et_login_username = findViewById(R.id.et_login_username);
        et_login_psw = findViewById(R.id.et_login_psw);
        login_view = findViewById(R.id.login_view);
        // 给组件添加监听器
        btn_login.setOnClickListener(this);
        btn_toRegister.setOnClickListener(this);
        et_login_username.setOnFocusChangeListener(this);
        et_login_psw.setOnFocusChangeListener(this);
        // 初始化数据库操作
        userDao = new UserDao(this);
    }

    private void setTimerListener() {
        intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK); // 每分钟变化
        intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED); // 设置了系统时区
        intentFilter.addAction(Intent.ACTION_TIME_CHANGED); // 设置了系统时间

        timeChangeReceiver = new TimeChangeReceiver();
        registerReceiver(timeChangeReceiver, intentFilter);
    }

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.btn_login) {
            // 获取输入的字符串
            String username = et_login_username.getText().toString();
            String passwd = et_login_psw.getText().toString();
            System.out.println(username);
            System.out.println(passwd);
            if(username.equals("")) {
                Toast.makeText(this, "请输入用户名", Toast.LENGTH_LONG).show();
            } else if(passwd.equals("")) {
                Toast.makeText(this, "请输入密码", Toast.LENGTH_LONG).show();
            } else {
                HashMap res = userDao.login(username, passwd);
                int code = Integer.parseInt(res.get("code").toString());
                System.out.println(res);
                if(code == 200) {
                    Toast.makeText(this, "登录成功", Toast.LENGTH_LONG).show();
                    // 将用户信息存入共享参数中
                    User user = new User();
                    user.set_id(Integer.parseInt(res.get("id").toString()));
                    user.setUsername(res.get("username").toString());
                    user.setPassword(res.get("password").toString());
                    user.setPhone(res.get("phone").toString());
                    user.setWordType(res.get("wordType").toString());
                    SPUtils.put(this, "User", JsonUtils.objectToJson(user));
                    assert(SPUtils.contains(this, "User") == true);
                    // 进入主页
                    Intent intent = new Intent();
                    intent.setClass(this, MainHomeActivity.class);
                    startActivity(intent);
                } else if(code == 500) {
                    Toast.makeText(this, "密码错误", Toast.LENGTH_LONG).show();
                } else if(code == 501) {
                    Toast.makeText(this, "该账号不存在", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, "登录失败，请重试", Toast.LENGTH_LONG).show();
                }
            }
        } else if(view.getId() == R.id.btn_toRegister) {
            Intent intent = new Intent();
            intent.setClass(this, RegisterActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        // 失去焦点时关闭软键盘
        if(!hasFocus) {
            ViewUtil.hideOneInputMethod(LoginActivity.this, view);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(timeChangeReceiver); // 摧毁界面时取消时间监听
    }

    class TimeChangeReceiver extends BroadcastReceiver { // 时间监听器
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Intent.ACTION_TIME_TICK:
                    // 每过一分钟触发
                    String res = (String) SPUtils.get(context, "bg", "");
                    switch (res) {
                        case "bg0":
                            login_view.setBackgroundResource(R.drawable.login_background);
                            SPUtils.put(context, "bg", "bg1");
                            break;
                        case "bg1":
                            login_view.setBackgroundResource(R.drawable.bg1);
                            SPUtils.put(context, "bg", "bg2");
                            break;
                        case "bg2":
                            login_view.setBackgroundResource(R.drawable.bg2);
                            SPUtils.put(context, "bg", "bg0");
                            break;
                    }
                    break;
                case Intent.ACTION_TIME_CHANGED:
                    // 设置了系统时间
                    Toast.makeText(context, "system time changed", Toast.LENGTH_SHORT).show();
                    break;
                case Intent.ACTION_TIMEZONE_CHANGED:
                    // 设置了系统时区的action
                    Toast.makeText(context, "system time zone changed", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }
}